using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using SSRSDeployer.ReportService2005;
using SSRSDeployer.Properties;

namespace SSRSDeployer
{
    public class ReportDeployer : ReportingServiceDeployer
    {
        public ReportDeployer(Dictionary<string, string> arguments) : base(arguments) { }

        protected override void ValidateArguments()
        {
            if (string.IsNullOrEmpty(ReportLocation))
                throw new NullReferenceException(Resources.NoReportLocation);

            if (!File.Exists(ReportLocation))
                throw new FileNotFoundException(Resources.ReportFileNotFound, ReportLocation);
        }

        public string ReportLocation
        {
            get { return Arguments["/irpt:"]; }
        }

        public string ReportName
        {
            get { return Path.GetFileNameWithoutExtension(ReportLocation); }
        }

        public override void Deploy()
        {
            byte[] reportDefinition = null;
            try
            {
                using (FileStream fs = File.OpenRead(ReportLocation))
                {
                    reportDefinition = new byte[fs.Length];
                    fs.Read(reportDefinition, 0, (int)fs.Length);
                    fs.Close();
                }
            }
            catch (IOException ex)
            {
                Console.WriteLine(ex.Message);
            }
            Warning[] warnings = null;
            try
            {
                if (this.CheckIfExists(ItemTypeEnum.Report, Parent, ReportName))
                    DeleteItem(Parent, ReportName);
                warnings = _rs.CreateReport(ReportName, Parent, true, reportDefinition, null);
                if (warnings != null && warnings.Length > 0)
                {
                    foreach (Warning warning in warnings)
                    {
                        Console.WriteLine(warning.Message);
                    }
                }
                Console.WriteLine(Resources.ReportPublishSuccess, ReportName);
            }
            catch(Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
    }
}
